package com.zhw.learning.thread;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author zhw
 */
public class Synchronized {

    static String getCurrentDate() {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return df.format(new Date());
    }

}

class SynchronizedTest implements Runnable {

    private static int counter = 1;

    public synchronized static void method() {
        String startDate = Synchronized.getCurrentDate();
        for (int i = 0; i < 5; i++) {
            try {
                System.out.println("线程 ：" + Thread.currentThread().getName() + " 当前计数器 ：" + (counter++));
                System.out.println("开始时间 ：" + startDate + " 当前时间 ：" + Synchronized.getCurrentDate());
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void run() {
        method();
    }

    public static void main(String[] args) {
        SynchronizedTest syncThread1 = new SynchronizedTest();
        SynchronizedTest syncThread2 = new SynchronizedTest();
        Thread thread1 = new Thread(syncThread1, "sync-thread-1");
        Thread thread2 = new Thread(syncThread2, "sync-thread-2");
        thread1.start();
        thread2.start();
    }

}

